// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package config_api_impl

import (
	"context"

	"gitcode.com/opendragonfly/df_proto_gen_go.git/config_api"
	"gitcode.com/opendragonfly/df_server/config"
	"gitcode.com/opendragonfly/df_server/dao/config_dao"
	"gitcode.com/opendragonfly/df_server/dao/member_dao"
	"github.com/dgraph-io/badger/v4"
)

func (apiImpl *ConfigApiImpl) GetAuthCheckState(ctx context.Context, req *config_api.GetAuthCheckStateRequest) (*config_api.GetAuthCheckStateResponse, error) {
	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}

	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//donothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &config_api.GetAuthCheckStateResponse{
				Code:   config_api.GetAuthCheckStateResponse_CODE_NO_REMOTE,
				ErrMsg: "鉴权服务器不存在",
			}, nil
		}
		_, _, err = member_dao.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &config_api.GetAuthCheckStateResponse{
				Code:   config_api.GetAuthCheckStateResponse_CODE_NO_PERMISSION,
				ErrMsg: "用户不存在",
			}, nil
		}
	}

	enable, err := config_dao.StateDao.Get()
	if err != nil {
		return nil, err
	}
	return &config_api.GetAuthCheckStateResponse{
		Code:   config_api.GetAuthCheckStateResponse_CODE_OK,
		Enable: enable,
	}, nil
}

func (apiImpl *ConfigApiImpl) EnableAuthCheck(ctx context.Context, req *config_api.EnableAuthCheckRequest) (*config_api.EnableAuthCheckResponse, error) {
	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}

	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &config_api.EnableAuthCheckResponse{
				Code:   config_api.EnableAuthCheckResponse_CODE_NO_REMOTE,
				ErrMsg: "鉴权服务器不存在",
			}, nil
		}
		_, localMember, err := member_dao.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &config_api.EnableAuthCheckResponse{
				Code:   config_api.EnableAuthCheckResponse_CODE_NO_PERMISSION,
				ErrMsg: "用户不存在",
			}, nil
		}
		if !localMember.Perm.ChangeAuthCheck {
			return &config_api.EnableAuthCheckResponse{
				Code:   config_api.EnableAuthCheckResponse_CODE_NO_PERMISSION,
				ErrMsg: "没有权限",
			}, nil
		}
	}
	err = config_dao.StateDao.Set(true)
	if err != nil {
		return nil, err
	}

	return &config_api.EnableAuthCheckResponse{
		Code: config_api.EnableAuthCheckResponse_CODE_OK,
	}, nil
}

func (apiImpl *ConfigApiImpl) DisableAuthCheck(ctx context.Context, req *config_api.DisableAuthCheckRequest) (*config_api.DisableAuthCheckResponse, error) {
	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &config_api.DisableAuthCheckResponse{
				Code:   config_api.DisableAuthCheckResponse_CODE_NO_REMOTE,
				ErrMsg: "鉴权服务器不存在",
			}, nil
		}
		_, localMember, err := member_dao.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &config_api.DisableAuthCheckResponse{
				Code:   config_api.DisableAuthCheckResponse_CODE_NO_PERMISSION,
				ErrMsg: "用户不存在",
			}, nil
		}
		if !localMember.Perm.ChangeAuthCheck {
			return &config_api.DisableAuthCheckResponse{
				Code:   config_api.DisableAuthCheckResponse_CODE_NO_PERMISSION,
				ErrMsg: "没有权限",
			}, nil
		}
	}
	err = config_dao.StateDao.Set(false)
	if err != nil {
		return nil, err
	}

	return &config_api.DisableAuthCheckResponse{
		Code: config_api.DisableAuthCheckResponse_CODE_OK,
	}, nil
}

func (apiImpl *ConfigApiImpl) AddAuthSecret(ctx context.Context, req *config_api.AddAuthSecretRequest) (*config_api.AddAuthSecretResponse, error) {
	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &config_api.AddAuthSecretResponse{
				Code:   config_api.AddAuthSecretResponse_CODE_NO_REMOTE,
				ErrMsg: "鉴权服务器不存在",
			}, nil
		}
		_, localMember, err := member_dao.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &config_api.AddAuthSecretResponse{
				Code:   config_api.AddAuthSecretResponse_CODE_NO_PERMISSION,
				ErrMsg: "用户不存在",
			}, nil
		}
		if !localMember.Perm.ManageAuthSecret {
			return &config_api.AddAuthSecretResponse{
				Code:   config_api.AddAuthSecretResponse_CODE_NO_PERMISSION,
				ErrMsg: "没有权限",
			}, nil
		}
	}
	_, err = config_dao.SecretDao.Get(req.AuthSecret.Username)
	if err != nil {
		if err != badger.ErrKeyNotFound {
			return nil, err
		}
	} else {
		return &config_api.AddAuthSecretResponse{
			Code:   config_api.AddAuthSecretResponse_CODE_EXIST_AUTH_SECRET,
			ErrMsg: "验证密钥已存在",
		}, nil
	}
	err = config_dao.SecretDao.Set(req.AuthSecret)
	if err != nil {
		return nil, err
	}
	return &config_api.AddAuthSecretResponse{
		Code: config_api.AddAuthSecretResponse_CODE_OK,
	}, nil
}

func (apiImpl *ConfigApiImpl) RemoveAuthSecret(ctx context.Context, req *config_api.RemoveAuthSecretRequest) (*config_api.RemoveAuthSecretResponse, error) {
	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &config_api.RemoveAuthSecretResponse{
				Code:   config_api.RemoveAuthSecretResponse_CODE_NO_REMOTE,
				ErrMsg: "鉴权服务器不存在",
			}, nil
		}
		_, localMember, err := member_dao.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &config_api.RemoveAuthSecretResponse{
				Code:   config_api.RemoveAuthSecretResponse_CODE_NO_PERMISSION,
				ErrMsg: "用户不存在",
			}, nil
		}
		if !localMember.Perm.ManageAuthSecret {
			return &config_api.RemoveAuthSecretResponse{
				Code:   config_api.RemoveAuthSecretResponse_CODE_NO_PERMISSION,
				ErrMsg: "没有权限",
			}, nil
		}
	}
	err = config_dao.SecretDao.Remove(req.Username)
	if err != nil {
		return nil, err
	}

	return &config_api.RemoveAuthSecretResponse{
		Code: config_api.RemoveAuthSecretResponse_CODE_OK,
	}, nil
}

func (apiImpl *ConfigApiImpl) UpdateAuthSecret(ctx context.Context, req *config_api.UpdateAuthSecretRequest) (*config_api.UpdateAuthSecretResponse, error) {
	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &config_api.UpdateAuthSecretResponse{
				Code:   config_api.UpdateAuthSecretResponse_CODE_NO_REMOTE,
				ErrMsg: "鉴权服务器不存在",
			}, nil
		}
		_, localMember, err := member_dao.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &config_api.UpdateAuthSecretResponse{
				Code:   config_api.UpdateAuthSecretResponse_CODE_NO_PERMISSION,
				ErrMsg: "用户不存在",
			}, nil
		}
		if !localMember.Perm.ManageAuthSecret {
			return &config_api.UpdateAuthSecretResponse{
				Code:   config_api.UpdateAuthSecretResponse_CODE_NO_PERMISSION,
				ErrMsg: "没有权限",
			}, nil
		}
	}
	_, err = config_dao.SecretDao.Get(req.AuthSecret.Username)
	if err != nil {
		if err == badger.ErrKeyNotFound {
			return &config_api.UpdateAuthSecretResponse{
				Code:   config_api.UpdateAuthSecretResponse_CODE_NO_AUTH_SECRET,
				ErrMsg: "验证密钥不存在",
			}, nil
		}
		return nil, err
	}

	err = config_dao.SecretDao.Set(req.AuthSecret)
	if err != nil {
		return nil, err
	}

	return &config_api.UpdateAuthSecretResponse{
		Code: config_api.UpdateAuthSecretResponse_CODE_OK,
	}, nil
}

func (apiImpl *ConfigApiImpl) GetAuthSecret(ctx context.Context, req *config_api.GetAuthSecretRequest) (*config_api.GetAuthSecretResponse, error) {
	emptyInfo := &config_api.AuthSecretInfo{}

	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &config_api.GetAuthSecretResponse{
				Code:       config_api.GetAuthSecretResponse_CODE_NO_REMOTE,
				ErrMsg:     "鉴权服务器不存在",
				AuthSecret: emptyInfo,
			}, nil
		}
		_, localMember, err := member_dao.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &config_api.GetAuthSecretResponse{
				Code:       config_api.GetAuthSecretResponse_CODE_NO_PERMISSION,
				ErrMsg:     "用户不存在",
				AuthSecret: emptyInfo,
			}, nil
		}
		if !localMember.Perm.ReadAuthSecret {
			return &config_api.GetAuthSecretResponse{
				Code:       config_api.GetAuthSecretResponse_CODE_NO_PERMISSION,
				ErrMsg:     "没有权限",
				AuthSecret: emptyInfo,
			}, nil
		}
	}
	secretItem, err := config_dao.SecretDao.Get(req.Username)
	if err != nil {
		if err == badger.ErrKeyNotFound {
			return &config_api.GetAuthSecretResponse{
				Code:       config_api.GetAuthSecretResponse_CODE_NO_AUTH_SECRET,
				ErrMsg:     "验证密钥不存在",
				AuthSecret: emptyInfo,
			}, nil
		}
		return nil, err
	}
	return &config_api.GetAuthSecretResponse{
		Code: config_api.GetAuthSecretResponse_CODE_OK,
		AuthSecret: &config_api.AuthSecretInfo{
			Username: secretItem.Username,
			Password: secretItem.Password,
		},
	}, nil
}

func (apiImpl *ConfigApiImpl) ListAuthSecret(ctx context.Context, req *config_api.ListAuthSecretRequest) (*config_api.ListAuthSecretResponse, error) {
	emptyList := []*config_api.AuthSecretInfo{}

	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &config_api.ListAuthSecretResponse{
				Code:           config_api.ListAuthSecretResponse_CODE_NO_REMOTE,
				ErrMsg:         "鉴权服务器不存在",
				AuthSecretList: emptyList,
			}, nil
		}
		_, localMember, err := member_dao.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &config_api.ListAuthSecretResponse{
				Code:           config_api.ListAuthSecretResponse_CODE_NO_PERMISSION,
				ErrMsg:         "用户不存在",
				AuthSecretList: emptyList,
			}, nil
		}
		if !localMember.Perm.ReadAuthSecret {
			return &config_api.ListAuthSecretResponse{
				Code:           config_api.ListAuthSecretResponse_CODE_NO_PERMISSION,
				ErrMsg:         "没有权限",
				AuthSecretList: emptyList,
			}, nil
		}
	}
	secreetList, err := config_dao.SecretDao.List()
	if err != nil {
		return nil, err
	}
	return &config_api.ListAuthSecretResponse{
		Code:           config_api.ListAuthSecretResponse_CODE_OK,
		AuthSecretList: secreetList,
	}, nil
}
